import { Controller, Post, Body, Get, Session, HttpStatus, HttpException } from '@nestjs/common';
import { UserService } from './user.service';
import * as CryptoJS from 'crypto-js';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) { }

  @Post('login')
  async login(@Body() loginDto: any, @Session() session: Record<string, any>) {
    const { username, password } = loginDto;
    console.log('Login attempt:', { username, passwordLength: password?.length });

    if (!username || !password) {
      console.log('Login failed: Missing username or password');
      return {
        code: 1,
        data: null,
        msg: '用户名或密码不能为空'
      };
    }

    const hashedPassword = CryptoJS.MD5(password.trim()).toString();
    console.log('Hashed password:', hashedPassword);

    const user = await this.userService.findOne(username, hashedPassword);
    console.log('User found:', user);

    if (!user) {
      console.log('Login failed: Invalid credentials');
      return {
        code: 1,
        data: null,
        msg: '用户名或密码错误'
      };
    }

    session.userId = user.id;
    console.log('Session created with userId:', user.id);

    return {
      code: 0,
      data: user.nickname,
      msg: 'success'
    };
  }

  @Post('register')
  async register(@Body() registerDto: any) {
    try {
      const user = await this.userService.register(registerDto);
      return {
        code: 0,
        data: null,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Get('loginOut')
  async logout(@Session() session: Record<string, any>) {
    session.userId = null;
    return {
      code: 0,
      data: null,
      msg: 'success'
    };
  }
} 